-- ============================================
-- INTRO - ROCKET CASINO (~10 secondes)
-- Tete de Miaouss avec piece + R, pokeball qui tourne (design
-- ameliore), pluie de pieces reconnaissables, eclairs en fond,
-- puis le titre ROCKET CASINO en gros pixels avec badges.
-- ============================================

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

local speaker = peripheral.find("speaker")  -- optionnel

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function clearScreen()
    term.setBackgroundColor(colors.black)
    term.clear()
end

local function fillBlock(x1, y1, x2, y2, color)
    term.setBackgroundColor(color)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", math.max(0, x2 - x1 + 1)))
    end
end

local function fillDisk(centerX, centerY, rRows, rColsFactor, color)
    local rCols = rRows * 2 * rColsFactor
    for dy = -rRows, rRows do
        local ny = dy / rRows
        local inside = 1 - ny * ny
        if inside > 0 then
            local dxMax = math.floor(rCols * math.sqrt(inside))
            fillBlock(centerX - dxMax, centerY + dy, centerX + dxMax, centerY + dy, color)
        end
    end
end

-- === MUSIQUE (boucle, en parallele) ===
local MELODY = {
    { note = "harp", pitch = 12, dur = 0.15 },
    { note = "harp", pitch = 14, dur = 0.15 },
    { note = "harp", pitch = 16, dur = 0.15 },
    { note = "bell", pitch = 19, dur = 0.30 },
    { note = "harp", pitch = 16, dur = 0.15 },
    { note = "harp", pitch = 14, dur = 0.15 },
    { note = "harp", pitch = 12, dur = 0.30 },
    { note = "harp", pitch = 9,  dur = 0.15 },
    { note = "harp", pitch = 12, dur = 0.15 },
    { note = "bell", pitch = 16, dur = 0.40 },
}

local function playMusic()
    if not speaker then return end
    while true do
        for _, n in ipairs(MELODY) do
            speaker.playNote(n.note, 1, n.pitch)
            sleep(n.dur)
        end
    end
end

-- === POLICE PIXEL-ART 5x5 (utilisee pour le R du miaouss et le titre) ===
local FONT = {
    R = { "11110", "10001", "11110", "10100", "10010" },
    O = { "01110", "10001", "10001", "10001", "01110" },
    C = { "01111", "10000", "10000", "10000", "01111" },
    K = { "10001", "10010", "11100", "10010", "10001" },
    E = { "11111", "10000", "11110", "10000", "11111" },
    T = { "11111", "00100", "00100", "00100", "00100" },
    A = { "01110", "10001", "11111", "10001", "10001" },
    S = { "01111", "10000", "01110", "00001", "11110" },
    I = { "11111", "00100", "00100", "00100", "11111" },
    N = { "10001", "11001", "10101", "10011", "10001" },
}

local function drawLetter(letter, x, y, pixelW, color)
    local pattern = FONT[letter]
    if not pattern then return end
    for row = 1, 5 do
        local line = pattern[row]
        for col = 1, 5 do
            if line:sub(col, col) == "1" then
                fillBlock(x + (col - 1) * pixelW, y + row - 1, x + (col - 1) * pixelW + pixelW - 1, y + row - 1, color)
            end
        end
    end
end

-- === GEOMETRIE GENERALE ===
local cx = math.floor(w / 2)
local cy = math.floor(h * 0.46)
local radiusRows = math.max(5, math.floor(h * 0.22))
radiusRows = math.min(radiusRows, math.floor(w * 0.20))

-- === SCENE 1 : TETE DE MIAOUSS AVEC PIECE + R ===
local function drawTriangleUp(apexX, topY, height, halfWidthBase, color)
    for row = 0, height - 1 do
        local width = (height > 1) and math.floor(halfWidthBase * (row / (height - 1))) or halfWidthBase
        fillBlock(apexX - width, topY + row, apexX + width, topY + row, color)
    end
end

local function drawMeowthHead()
    local faceR = radiusRows
    local faceColsHalf = faceR * 2

    -- oreilles (triangles pointus au-dessus du visage)
    local earHeight = math.floor(faceR * 0.7)
    local earHalfWidth = math.floor(faceR * 0.4)
    local earOffsetX = math.floor(faceColsHalf * 0.55)
    local earTopY = cy - faceR - earHeight + 3
    drawTriangleUp(cx - earOffsetX, earTopY, earHeight, earHalfWidth, colors.yellow)
    drawTriangleUp(cx + earOffsetX, earTopY, earHeight, earHalfWidth, colors.yellow)

    -- visage (rond creme), pas de traits de visage
    fillDisk(cx, cy, faceR, 1.0, colors.yellow)

    -- grand R rouge bien centre au milieu de la tete
    local pixelW = math.max(1, math.floor(faceR / 4))
    local letterSize = 5 * pixelW
    drawLetter("R", cx - math.floor(letterSize / 2), cy - math.floor(letterSize / 2), pixelW, colors.red)
end

local function playMeowthIntro()
    clearScreen()
    drawMeowthHead()
    if speaker then speaker.playNote("harp", 1, 6) end
    sleep(2.5)
end

-- === ECLAIRS EN ARRIERE-PLAN ===
local function buildBolt(xBase, rows)
    local bolt = {}
    local x = xBase
    for row = 1, rows do
        x = x + math.random(-1, 1)
        table.insert(bolt, { x = x, y = row })
    end
    return bolt
end

local boltRows = math.floor(h * 0.4)
local boltLeft = buildBolt(math.max(2, math.floor(w * 0.08)), boltRows)
local boltRight = buildBolt(math.max(2, math.floor(w * 0.90)), boltRows)

local function drawBolt(bolt, visible)
    local color
    if visible then
        color = (math.random(2) == 1) and colors.white or colors.lightBlue
    else
        color = colors.black
    end
    term.setBackgroundColor(color)
    for _, p in ipairs(bolt) do
        if p.x >= 1 and p.x <= w and p.y >= 1 and p.y <= h then
            term.setCursorPos(p.x, p.y)
            term.write(" ")
        end
    end
end

-- === PIECES QUI TOMBENT (forme ronde reconnaissable, pas un carre plat) ===
local function newDrop()
    return { x = math.random(1, math.max(1, w - 3)), y = math.random(-14, 0) }
end

local function makeDrops(count)
    local drops = {}
    for i = 1, count do
        drops[i] = newDrop()
    end
    return drops
end

local function drawCoin(x, y)
    term.setBackgroundColor(colors.orange)
    term.setCursorPos(x, y); term.write(" ")
    term.setBackgroundColor(colors.yellow)
    term.setCursorPos(x + 1, y); term.write(" ")
    term.setBackgroundColor(colors.orange)
    term.setCursorPos(x + 2, y); term.write(" ")
    term.setCursorPos(x, y + 1); term.write(" ")
    term.setCursorPos(x + 1, y + 1); term.write(" ")
    term.setCursorPos(x + 2, y + 1); term.write(" ")
end

local function updateAndDrawDrops(drops)
    for _, d in ipairs(drops) do
        d.y = d.y + 1
        if d.y > h then
            local nd = newDrop()
            d.x, d.y = nd.x, nd.y
        elseif d.y >= 1 then
            drawCoin(d.x, d.y)
        end
    end
end

-- === POKEBALL (design ameliore : bouton rond au lieu d'un rectangle) ===
local SPIN_FRAMES = {
    { squish = 1.00, sign = 1 },
    { squish = 0.70, sign = 1 },
    { squish = 0.35, sign = 1 },
    { squish = 0.10, sign = 1 },
    { squish = 0.35, sign = -1 },
    { squish = 0.70, sign = -1 },
    { squish = 1.00, sign = -1 },
}

local function drawPokeball(frame)
    local radiusColsFull = radiusRows * 2
    local radiusCols = math.max(1, math.floor(radiusColsFull * frame.squish))
    local buttonRadiusCols = math.max(2, math.floor(radiusColsFull * 0.16))
    local buttonOffset = frame.sign * math.floor(radiusColsFull * (1 - frame.squish) * 0.6)

    for dy = -radiusRows, radiusRows do
        local ny = dy / radiusRows
        local inside = 1 - ny * ny
        if inside > 0 then
            local dxMax = math.floor(radiusCols * math.sqrt(inside))
            for dx = -dxMax, dxMax do
                local color
                if math.abs(dy) <= 1 then
                    -- bande noire + bouton rond
                    local by = dy / 1.3
                    local bInside = 1 - by * by
                    if bInside > 0 and math.abs(dx - buttonOffset) <= buttonRadiusCols * math.sqrt(bInside) then
                        color = colors.lightGray
                    else
                        color = colors.black
                    end
                elseif dy < 0 then
                    color = colors.red
                else
                    color = colors.white
                end
                term.setBackgroundColor(color)
                term.setCursorPos(cx + dx, cy + dy)
                term.write(" ")
            end
        end
    end
end

local function playPokeballPhase(cycles, tick)
    local drops = makeDrops(18)
    local t = 0

    for c = 1, cycles do
        for _, frame in ipairs(SPIN_FRAMES) do
            t = t + 1
            clearScreen()

            local lightningOn = (t % 5 == 0)
            drawBolt(boltLeft, lightningOn)
            drawBolt(boltRight, lightningOn)

            updateAndDrawDrops(drops)
            drawPokeball(frame)

            sleep(tick)
        end
    end
end

-- === TITRE "ROCKET CASINO" EN GROS PIXELS AVEC BADGES ===
local function choosePixelWidth()
    for _, pw in ipairs({ 4, 3, 2, 1 }) do
        if 43 * pw <= (w - 4) then return pw end
    end
    return 1
end

local function drawWord(word, topY, pixelW, letterColor, badgeBg, badgeBorder, badgeLetterColor)
    local letterW = 5 * pixelW
    local gap = pixelW
    local totalW = #word * letterW + (#word - 1) * gap
    local startX = math.floor((w - totalW) / 2) + 1

    local x = startX
    for i = 1, #word do
        local ch = word:sub(i, i)
        local pattern = FONT[ch]
        local isBadgeLetter = (i == 1)

        if isBadgeLetter and pattern then
            local x1 = x - 2 * pixelW
            local y1 = topY - 1
            local x2 = x + letterW - 1 + 2 * pixelW
            local y2 = topY + 5 - 1 + 1
            fillBlock(x1, y1, x2, y2, badgeBorder)
            fillBlock(x1 + pixelW, y1 + 1, x2 - pixelW, y2 - 1, badgeBg)
        end

        if pattern then
            local color = isBadgeLetter and badgeLetterColor or letterColor
            drawLetter(ch, x, topY, pixelW, color)
        end

        x = x + letterW + gap
    end
end

local function playTitleReveal()
    local pixelW = choosePixelWidth()
    local lineH = 5
    local gapBetweenLines = 3
    local totalH = lineH * 2 + gapBetweenLines
    local topY = math.floor((h - totalH) / 2) + 1

    if speaker then speaker.playNote("bell", 1, 8) end
    drawWord("ROCKET", topY, pixelW, colors.yellow, colors.red, colors.white, colors.white)
    sleep(0.5)
    if speaker then speaker.playNote("bell", 1, 14) end
    drawWord("CASINO", topY + lineH + gapBetweenLines, pixelW, colors.yellow, colors.red, colors.white, colors.white)
    if speaker then speaker.playNote("bell", 1, 19) end
end

-- === SEQUENCE PRINCIPALE (~10 secondes au total) ===
local function mainSequence()
    playMeowthIntro()                 -- ~2.5s
    clearScreen()
    playPokeballPhase(3, 0.17)        -- 3 cycles x 7 frames x 0.17s ~= 3.6s
    clearScreen()
    fillBlock(1, 1, w, h, colors.black)
    playTitleReveal()                 -- ~0.5s
    sleep(3.4)                        -- hold final, total ~= 10s
end

-- === PROGRAMME PRINCIPAL (boucle en continu) ===
-- Astuce : Ctrl+T sur le computer pour arreter l'animation.
if speaker then
    while true do
        parallel.waitForAny(playMusic, mainSequence)
    end
else
    while true do
        mainSequence()
    end
end